require('./PageDelivernotice.styl');
const classNames = require("classnames")
import { Control } from 'react-keeper'
const reactMixin = require('react-mixin');
const Actions = require('./actions');
const Store = require('./store');
import { Group, TextField, TextareaField, Boxs, Datetime, Switch, Field, NavBar, Toast } from 'saltui';
import Icon from 'salt-icon';
import { dealTime} from 'clientConfig/util/queryurlfield';
const { HBox, Box, VBox } = Boxs;
const GetUserList = require('components/getuserslist');
const Uploadimg = require('components/uploadimg');
// var count = 0;
const getTime = (time) => {
    let date_obj = new Date(time);
    const sup = (n) => { return (n < 10) ? '0' + n : n; }
    var date = date_obj.getFullYear() + "." + sup(date_obj.getMonth() + 1) + "." + sup(date_obj.getDate());
    return (date + " " + sup(date_obj.getHours()) + ":" + sup(date_obj.getMinutes()));
}
class Delivernotice extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            wordcount: 0,
            title: '',//标题
            content: '',//通知内容
            reply: false,//允许回复
            signature: '',//署名
            getuserslist: false,
            listData: [],//查看发布对象人员列表
            selectPersons: 0,//发布人信息
            value: '',//时间
            selecttime: false,
        };
        this.datetimeProps = {
            locale: 'zh-cn',
        };
        this.handleClickPublish = this.handleClickPublish.bind(this);
        this.handleGetUsersList = this.handleGetUsersList.bind(this);
        this.handleUserCancle = this.handleUserCancle.bind(this);
        this.handleOnRightClick = this.handleOnRightClick.bind(this);
        this.handleOnLeftClick = this.handleOnLeftClick.bind(this);
        this.focus = this.focus.bind(this)
        this.blur = this.blur.bind(this);
    }
    handleTextChange(name, newValue) {
        this.setState({
            [name]: newValue,
        }, () => {
            if (name == 'content') {
                this.setState({ wordcount: this.state.content.length })
            }
        });
    }
    //时间选择器选择
    handleChange(name, value) {
        this.setState({
            [name + '1']: new Date(value).toLocaleDateString(),
            [name]: value
        }, () => {
            if (name = "selecttime" && this.state.selecttime) {
                this.showSlot("slot1");
            } else if (name = "selecttime" && !this.state.selecttime) {
                this.setState({ value: { value: '' }, value1: '' })
            }
        });
    }
    //发布对象
    handleClickPublish() {
        this.setState((prevState) => ({ getuserslist: !prevState.getuserslist }))
    }
    //获取人员列表
    handleGetUsersList() {
        // count++;
        // if(count>1)return;
        Actions.getOrgListInfo();
    }
    //回传页面数据
    handleUserCancle(users) {
        if (users && users instanceof Array) {
            this.users = users;
            this.setState({ selectPersons: users.length })
        }
        this.setState({ getuserslist: false })
    }
    handleOnRightClick() {
        if (!this.state.title) {
            Toast.show({
                type: 'error',
                content: '未输入通知标题'
            });
            return;
        } else if (!this.state.content) {
            Toast.show({
                type: 'error',
                content: '未输入通知内容'
            });
            return;
        } else if (!this.state.selectPersons) {
            Toast.show({
                type: 'error',
                content: '未选择发布对象'
            });
            return;
        }
        let formData = new FormData(this.refs.uploadimg.refs.imageForm);
        const { title, content, reply, signature, value } = this.state;
        if (value && value.value) {
            var time = getTime(value.value)
        }else{
            var time = '';
        }
        Actions.delivernotice({ title, content, reply, signature, value: time, formData, users: this.users });
    }
    handleOnLeftClick() {
        Control.go(-1)
    }
    onConfirm(value, id) {
        // var time = new Date(value.value).toLocaleDateString() + " " + new Date(value.value).toTimeString().split(" ")[0];
        var time = dealTime(value.value)
        this.setState({
            [id]: value,
            [id + '1']: time
        });
    }

    onCancel(id) {
        console.log('cancel', this.state[id]);
    }
    //显示日期
    showSlot(id) {
        this[id].show();
    }
    focus(id) {
        let t = this;
        if (navigator.userAgent.indexOf('Android') != -1) {
            return;
        }
        let top = document.body.scrollTop;
        let timer = setTimeout(function () {
            let objElement = ReactDOM.findDOMNode(t.refs.navBar)
            objElement.scrollTop = document.body.scrollHeight;
            if (id == "content" || id == "title") {
                if (objElement) {
                    objElement.scrollIntoViewIfNeeded(true);
                    clearTimeout(timer);
                }
            } else {
                const scrollHandler = function (e) {
                    let dom = ReactDOM.findDOMNode(t.refs.textfieldSignature);
                    dom.getElementsByClassName("t-text-field-input")[0].blur();
                }
                window.addEventListener('scroll', scrollHandler);
                objElement.style.top = (document.body.scrollTop - top) + 'px';
            }
        }, 0);
    }
    blur() {
        let t = this;
        if (navigator.userAgent.indexOf('Android') != -1) {
            return;
        }
        let objElement = ReactDOM.findDOMNode(t.refs.navBar);
        objElement.style.top = '0px';
        window.removeEventListener("scroll");
    }
    render() {
        let t = this;
        return (
            <div className="delivernotice t-PT60">
                <NavBar
                    className={classNames({ "ios-nav-bar": window.isIphone })}
                    isShow={false}
                    onLeftClick={this.handleOnLeftClick}
                    onRightClick={this.handleOnRightClick}
                    rightText="发布"
                    title="发布通知"
                    ref="navBar"
                />
                <Group >
                    <Group.List >
                        <TextField
                            label=""
                            placeholder="请输入通知标题"
                            value={t.state.title}
                            tip=""
                            rightText='发布'
                            onChange={t.handleTextChange.bind(t, 'title')}
                            onFocus={this.focus.bind(t, 'title')}
                        />
                    </Group.List>
                    <Group.List>
                        <TextareaField
                            layout="h"
                            label=""
                            minRows={2}
                            maxRows={5}
                            placeholder="请输入内容"
                            value={t.state.content}
                            tip={<div className="word-color"><span>{this.state.wordcount}</span>/200字</div>}
                            onChange={t.handleTextChange.bind(t, 'content')}
                            onFocus={this.focus.bind(t, 'content')}
                        />
                    </Group.List>
                </Group >
                <Group className="t-MT10">
                    <div onClick={this.handleClickPublish}>
                        <Group.List >
                            <Field label="请选择发布对象" icon={<Icon name="angle-right" />} tappable={true}>
                                {this.state.selectPersons > 0 ? <div >已选择{this.state.selectPersons}人</div> : null}
                            </Field>
                        </Group.List>
                    </div>
                    <Uploadimg ref="uploadimg" />
                </Group>
                <Group className="t-MT10">
                    <Group.List >
                        <Field label="允许回复" icon={<Switch on={this.state.reply} onChange={this.handleChange.bind(this, 'reply')} />} />
                    </Group.List>
                    <Group.List className="t-LH44">
                        {/* <DatetimeField label="定时发送" onSelect={t.handleChange.bind(t, 'value')} value={t.state.value} columns={DatetimeField.YMDHM} /> */}
                        <HBox vAlign="center" className="t-PL16 t-PR16">
                            <Box flex={1} className="fs16">定时发送</Box>
                            <Box flex={3} className="t-FAC">
                                <label>{t.state.value1}</label>
                                <Datetime
                                    {...this.datetimeProps}
                                    slotRef={s => t.slot1 = s}
                                    title="时间选择"
                                    value={t.state.value1}
                                    columns={Datetime.YMDWHM}
                                    onConfirm={(value) => { this.onConfirm(value, 'value'); }}
                                    onCancel={() => { this.onCancel('value'); }}
                                />
                            </Box>
                            <Box flex={1} className="my-switch">
                                <Switch on={this.state.selecttime} onChange={this.handleChange.bind(this, 'selecttime')} />
                            </Box>
                        </HBox>
                    </Group.List>
                    <Group.List >
                        <TextField
                            ref="textfieldSignature"
                            label="填写署名"
                            placeholder="选填"
                            value={t.state.signature}
                            tip=""
                            onChange={t.handleTextChange.bind(t, 'signature')}
                            onFocus={this.focus.bind(t, 'signature')}
                            onBlur={this.blur.bind(t, 'signature')}
                        />
                    </Group.List>
                </Group>
                {this.state.getuserslist
                    &&
                    <GetUserList
                        active={this.state.getuserslist}
                        handleGetUsersList={this.handleGetUsersList}
                        handleUserCancle={this.handleUserCancle}
                        listData={this.state.listData}
                    />}
            </div>
        );
    }

    componentWillMount() {
    }

    componentDidMount() {

    }

    componentWillReceiveProps(nextProps) {
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
    }

    componentDidUpdate(prevProps, prevState) {
    }

    componentWillUnmount() {
    }
}

reactMixin.onClass(Delivernotice, Reflux.connect(Store));

module.exports = Delivernotice;
